<template>
	<el-form
		:model="ruleForm"
		status-icon
		:rules="rules"
		ref="ruleForm"
		label-width="100px"
	>
		<el-form-item label="账户" prop="user">
			<el-input v-model="ruleForm.user"></el-input>
		</el-form-item>

		<el-form-item label="密码" prop="pass">
			<el-input
				type="password"
				v-model="ruleForm.pass"
				autocomplete="off"
			></el-input>
		</el-form-item>

		<el-form-item>
			<el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
		</el-form-item>
	</el-form>
</template>

<script>
import axios from 'axios'

export default {
	data() {
		// 对账户校验
		var checkUser = (rule, value, callback) => {
			let user = value.trim()
			if (!user) {
				return callback(new Error('账户不能为空'))
			} else if (user.length < 2 || user.length > 10) {
				return callback(new Error('账户长度在2-10位间'))
			} else {
				return callback()
			}
		}
		// 对密码校验
		var validatePass = (rule, value, callback) => {
			if (value.trim() === '' || value.length < 6 || value.length > 20) {
				callback(new Error('密码长度在6-20位之间'))
			} else {
				callback()
			}
		}

		return {
			ruleForm: {
				pass: '',
				user: '',
			},
			// 规则：校验表单
			rules: {
				pass: [{ validator: validatePass, trigger: 'blur' }],
				user: [{ validator: checkUser, trigger: 'blur' }],
			},
		}
	},
	methods: {
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
					// 发起一个请求
					axios.get('/data.json').then((res) => {
						// console.log(res)
						// 子传父一个标记，让父组件切换显示home页面
						this.$emit('getshow', 'home')
					})
				} else {
					this.$message.error('表单没有通过校验！')
					return false
				}
			})
		},
	},
}
</script>